package com.yingside.jdbc;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class TestQuery {
    public static void main(String[] args) {
        //1.先导入jar包

        //2.导入驱动，jdk1.8之后的版本，j2se程序可以省略，但是建议还是写上
        //com.mysql.cj.jdbc.Driver 这个路径实际就是找到Driver这个类
        //注意该路径是mysql8.0以后的jar包
        //如果是mysql5.7以前的jar，路径是com.mysql.jdbc.Driver
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Connection conn = null;
        Statement stmt = null;
        //结果集(游标)
        ResultSet rs = null;
        String url = "jdbc:mysql://47.108.158.110:3306/j181db";
        String user = "root";
        String password = "123456";

        List<Teacher> list = new ArrayList<Teacher>();

        try {
            //3.获取连接
            conn = DriverManager.getConnection(url,user,password);

            //4.获取stmt对象
            stmt = conn.createStatement();

            //5.执行sql语句
            String sql = "select teacher_id,teacher_name,teacher_tel,teacher_birthday,teacher_sex,teacher_age  from t_teacher";

            //查询是单独的一个方法executeQuery
            //查询成功会返回游标
            rs = stmt.executeQuery(sql);

            while(rs.next()){

//                int teacher_id = rs.getInt(1);
//                String teacher_name = rs.getString(2);
                int teacher_id = rs.getInt("teacher_id");
                String teacher_name = rs.getString("teacher_name");
                String teacher_tel = rs.getString("teacher_tel");
                String teacher_birthday = rs.getString("teacher_birthday");
                String teacher_sex = rs.getString("teacher_sex");
                int teacher_age = rs.getInt("teacher_age");

                Teacher t = new Teacher(teacher_id,teacher_name,teacher_tel,teacher_birthday,teacher_sex,teacher_age);
                list.add(t);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        for (int i = 0; i < list.size(); i++) {
            Teacher t = list.get(i);

            System.out.println("t = " + t);
        }


    }
}
